package user03.controller;

import common05.common.Results;
import common05.utils.StringUtils;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import user03.model.TUser;
import user03.service.TUserService;
import user03.vo.ChangePassVO;

@RestController
@RequestMapping("/t/user")
public class TUserController {

    @Autowired
    private TUserService tUserService;


    @PostMapping("change/pass")
    public Results changePass(@RequestBody(required = false) ChangePassVO vo) {
        if (vo == null || StringUtils.isNull(vo.getUsername())) {
            return Results.param_error("用户名不能为空");
        }

        if (StringUtils.isNull(vo.getOldPassword())) {
            return Results.param_error("旧密码不能为空");
        }

        if (StringUtils.isNull(vo.getNewPassword())) {
            return Results.param_error("新密码不能为空");
        }

        TUser tUser = tUserService.selectByUsername(vo.getUsername());

        if (tUser == null) {
            return Results.param_error("用户不存在");
        }

        if (!(DigestUtils.sha256Hex(vo.getOldPassword())).equals(tUser.getPassword())) {
            return Results.param_error("旧密码错误");
        }

        return Results.success(tUserService.updatePasswordById(tUser.getId(), vo.getNewPassword()));
    }

}
